package com.yuxl.common.auth.controller;


import com.yuxl.common.auth.domain.UserInfo;
import com.yuxl.common.core.annotation.Anonymous;
import com.yuxl.common.auth.domain.LoginUser;
import com.yuxl.common.auth.domain.RefreshToken;
import com.yuxl.common.core.domain.R;
import com.yuxl.common.auth.domain.Token;
import com.yuxl.common.auth.service.SecurityService;
import com.yuxl.common.auth.utils.JwtUtil;
import com.yuxl.common.core.domain.auth.JwtUser;
import com.yuxl.common.core.handler.ApiException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * @author yuxl
 */
@Tag(name = "安全接口")
@RequestMapping("/security")
@RestController
public class SecurityController {


    @Resource
    private SecurityService securityService;

    @Resource
    private JwtUtil jwtUtil;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    @Anonymous
    public Mono<R<Token>> login(@RequestBody LoginUser loginUser) {
        return securityService.login(loginUser)
                .map(R::ok);
    }

    @Operation(summary = "刷新token")
    @PostMapping("/refresh")
    @Anonymous
    public Mono<R<Token>> refresh(@RequestBody RefreshToken body) {
        if (StringUtils.isEmpty(body.refreshToken())) {
            return Mono.error(new ApiException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "刷新token无效"));
        }
        return securityService.refreshToken(body.refreshToken())
                .map(R::ok);
    }

    @Operation(summary = "用户登出", description = "删除token白名单，前端需删除本地token")
    @PostMapping("/logout")
    @Anonymous
    public Mono<R<Long>> logout(ServerHttpRequest request) {
        String token = jwtUtil.getToken(request);
        if(StringUtils.isNotEmpty(token)){
            return securityService.logout(token)
                    .map(R::ok);
        }
        return Mono.just(R.ok(0L));
    }


    @Operation(summary = "查询当前用户")
    @GetMapping
    public Mono<R<JwtUser>> getInfo() {
        return securityService.getCurrentUser()
                .map(R::ok);
    }



}
